import { RUNNING, KEY_MEM_RUNNING_CHILD } from '../constants';
import Tick from '../core/Tick';
import Gate from './Gate';

export default abstract class MemGate extends Gate {

    onOpen(tick: Tick, ...args: any[]) {
        tick.blackboard.set(KEY_MEM_RUNNING_CHILD, 0, tick.tree.id, this.id);
    }

    onTick(tick: Tick, ...args: any[]) {
        const child = tick.blackboard.get(KEY_MEM_RUNNING_CHILD, tick.tree.id, this.id);
        for (let i = child; i < this.children.length; i++) {
            const status = this.children[i].execute(tick, ...args);
            // 判断是否为拦截
            if (this.isInterrupt(status)) {
                return status
            }
            // 判断是RUNNING,表示当前需要等待,不进行接下来的执行和判断,等下次onTick,直接从上次(本次)的RUNNING进行执行
            if (status === RUNNING) {
                tick.blackboard.set(KEY_MEM_RUNNING_CHILD, i, tick.tree.id, this.id);
                return RUNNING;
            }
            // 判断是否不为忽略的状态
            if (!this.isIgnore(status)) {
                return status;
            }
        }
        // 返回默认类型
        return this.defaultStatus();
    }
};
